﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Squog_1._1
{
    class MyMath
    {
        public static Vector2 Projection(Vector2 U, Vector2 V)
        {
            V.Normalize();
            return Vector2.Dot(U, V) * V;
        }
        public static bool IsOpposite(Vector2 U, Vector2 V)
        {
            return Vector2.Dot(U, V) <= 0;
        }
        public static float AngleOf(LineSegment Line)
        {
            return AngleOf(Line.Direction);
        }
        public static float AngleOf(Vector2 V)
        {
            double theta = Math.Atan2(V.Y, V.X);

            if (theta < 0)
            {
                theta += MathHelper.TwoPi;
            }

            return (float)theta;
        }
        public static bool LeftOf(LineSegment Line, Vector2 Point)
        {
            Vector2 V2 = Line.point2 - Line.point1;
            Vector2 U2 = Point - Line.point1;
            Vector3 V = new Vector3(V2.X, V2.Y, 0);
            Vector3 U = new Vector3(U2.X, U2.Y, 0);

            Vector3 CrossVU = Vector3.Cross(V, U);

            return CrossVU.Z <= 0.1f;
        }
        public static bool LeftOf(LineSegment Line1, LineSegment Line2)
        {
            return LeftOf(Line1, Line2.point1) && LeftOf(Line1, Line2.point2);
        }
        public static float Area2(Vector2 V, Vector2 U)
        {
            Vector3 V3 = new Vector3(V.X, V.Y, 0);
            Vector3 U3 = new Vector3(U.X, U.Y, 0);

            return Vector3.Cross(V3, U3).Z;
        }
        public static Vector2 CollisionPoint(Vector2 Position, Vector2 Ray, LineSegment Line)
        {
            //TODO: Implement this
            if (Ray == Vector2.Zero)
                return Position;

            Vector2 V = new Vector2();

            if (Ray.X == 0)
            {
                float m = Line.Direction.Y / Line.Direction.X;

                V.X = Position.X;
                V.Y = m * (V.X - Line.point1.X) + Line.point1.Y;
            }
            else
            {

                float m1 = Ray.Y / Ray.X;
                float m2 = Line.Direction.Y / Line.Direction.X;

                if (m1 == m2)
                    return Position + Ray;

                V.X = (-m2 * Line.point1.X) + Line.point1.Y + (m1 * Position.X) - Position.Y;
                V.X = V.X / (m1 - m2);
                V.Y = m1 * (V.X - Position.X) + Position.Y;
            }

            if (float.IsNaN(V.X) || float.IsNaN(V.Y) || float.IsInfinity(V.X) || float.IsInfinity(V.Y))
            {
                throw new Exception("Position is NaN or Infinity");
            }

            return V;
        }
    }
}
